﻿using Coldairarrow.Entity;
using Coldairarrow.Entity.Goods;
using Coldairarrow.Entity.TurnPDF;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Coldairarrow.Util.DbHelpers;
using Coldairarrow.Util.PageSql;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business
{
    public class Warehouse_InformationBusiness : BaseBusiness<Warehouse_Information>, IWarehouse_InformationBusiness, ITransientDependency
    {
        readonly IOperator _Operator;
        public Warehouse_InformationBusiness(IDbAccessor db, IOperator Operators)
            : base(db)
        {
            _Operator = Operators;
        }
        #region 后台 ---接口
        #region 外部接口

        public async Task<PageResult<Warehouse_Information>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<Warehouse_Information>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {

                var newWhere = DynamicExpressionParser.ParseLambda<Warehouse_Information, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }
            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<Warehouse_Information> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(Warehouse_Information data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(Warehouse_Information data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }
        /// <summary>
        /// 获取入库明细
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<Warehouse_InformationDto>> GetOutData(PageInput<ConditionDTO> input)
        {
            /*
             2.
            */
            //库存信息表
            //获取入库信息
            var res = input.Search;
            //获取各种入库信息
            try
            {

                var k = SqlPage.GetPageResut(sqlstr, input.PageIndex, input.PageRows);
                var result = DbHelperSQL.QueryForList<Warehouse_InformationDto>(k).OrderByDescending(x => x.CreateTime).ToList();
                //获取数量
                int count = DbHelperSQL.QueryForList<Warehouse_Information>(strCount).Count;

                return new PageResult<Warehouse_InformationDto> { Data = result, Total = count };

            }
            catch (Exception e)
            {

                throw e;
            }
        }

        public Warehouse_InformationDto GetTheData1(InputDTO input)
        {
            var result = GetIQueryable().Where(q => q.Id == input.id).FirstOrDefault();
            Warehouse_InformationDto data = new Warehouse_InformationDto()
            {
                Id = result.Id,
                CreateTime = result.CreateTime,
                ProductName = Db.GetIQueryable<BTB_Goods>().Where(q => q.ID == result.Product_Id).FirstOrDefault().GoodsName,
                ProductsName = Db.GetIQueryable<BTB_GoodsSpecificationsItem>().Where(q => q.GoodsSpecificationsItemID == result.Products_Id).FirstOrDefault().GoodsSpecifications,
                Num = result.Num,
                Price = Db.GetIQueryable<BTB_GoodsSpecificationsItem>().Where(q => q.GoodsSpecificationsItemID == result.Products_Id).FirstOrDefault().Price,
                sumPrice = Db.GetIQueryable<BTB_GoodsSpecificationsItem>().Where(q => q.GoodsSpecificationsItemID == result.Products_Id).FirstOrDefault().Price * result.Num,
                Info_Oldbalance = result.Info_Oldbalance,
                ThisBlance = result.Num + result.Info_Oldbalance
            };
            return data;
        }
        public Warehouse_InformationDto GetTheData2(InputDTO input)
        {
            var result = GetIQueryable().Where(q => q.Id == input.id).FirstOrDefault();
            Warehouse_InformationDto data = new Warehouse_InformationDto()
            {
                Id = result.Id,
                ProductName = Db.GetIQueryable<BTB_Goods>().Where(q => q.ID == result.Product_Id).FirstOrDefault().GoodsName,
                ProductsName = Db.GetIQueryable<BTB_GoodsSpecificationsItem>().Where(q => q.GoodsSpecificationsItemID == result.Products_Id).FirstOrDefault().GoodsSpecifications,
                Num = result.Num + result.Info_Oldbalance,
                Price = Db.GetIQueryable<BTB_GoodsSpecificationsItem>().Where(q => q.GoodsSpecificationsItemID == result.Products_Id).FirstOrDefault().Price,
                DATA0 = result.DATA0
            };
            return data;
        }
        public Warehouse_InformationDto GetTheData3(InputDTO input)
        {
            var result = GetIQueryable().Where(q => q.Id == input.id).FirstOrDefault();
            Warehouse_InformationDto data = new Warehouse_InformationDto()
            {
                Id = result.Id,
                CreateTime = result.CreateTime,
                ProductName = Db.GetIQueryable<BTB_Goods>().Where(q => q.ID == result.Product_Id).FirstOrDefault().GoodsName,
                ProductsName = Db.GetIQueryable<BTB_GoodsSpecificationsItem>().Where(q => q.GoodsSpecificationsItemID == result.Products_Id).FirstOrDefault().GoodsSpecifications,
                Num = result.Num,
                Price = Db.GetIQueryable<BTB_GoodsSpecificationsItem>().Where(q => q.GoodsSpecificationsItemID == result.Products_Id).FirstOrDefault().Price,
                sumPrice = Db.GetIQueryable<BTB_GoodsSpecificationsItem>().Where(q => q.GoodsSpecificationsItemID == result.Products_Id).FirstOrDefault().Price * result.Num,
                Info_Oldbalance = result.Info_Oldbalance,
                ThisBlance = result.Num + result.Info_Oldbalance
            };
            return data;
        }
        public Warehouse_InformationDto GetTheData4(InputDTO input)
        {
            var result = GetIQueryable().Where(q => q.Id == input.id).FirstOrDefault();
            Warehouse_InformationDto data = new Warehouse_InformationDto()
            {
                Id = result.Id,
                CreateTime = result.CreateTime,
                ProductName = Db.GetIQueryable<BTB_Goods>().Where(q => q.ID == result.Product_Id).FirstOrDefault().GoodsName,
                ProductsName = Db.GetIQueryable<BTB_GoodsSpecificationsItem>().Where(q => q.GoodsSpecificationsItemID == result.Products_Id).FirstOrDefault().GoodsSpecifications,
                Num = result.Num,
                Price = Db.GetIQueryable<BTB_GoodsSpecificationsItem>().Where(q => q.GoodsSpecificationsItemID == result.Products_Id).FirstOrDefault().Price,
                sumPrice = Db.GetIQueryable<BTB_GoodsSpecificationsItem>().Where(q => q.GoodsSpecificationsItemID == result.Products_Id).FirstOrDefault().Price * result.Num,
                Info_Oldbalance = result.Info_Oldbalance,
                ThisBlance = result.Num + result.Info_Oldbalance
            };
            return data;
        }



        /// <summary>
        /// 入库
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task AddDataTwoAsync(Warehouse_Information data)
        {
            /*
             1.添加入库，
             2. 更改库存量
             */

            string id = IdHelper.GetId();
            DateTime creatime = DateTime.Now;
            string CreatId = _Operator.UserId;

            if (data.Num != null && data.Products_Id != null && data.Product_Id != null)
            {
                string str = $"execute WarehoseInsert '{id}','{data.Products_Id}','{creatime}','{CreatId}',{data.Num},0,'{data.Product_Id}','{data.SupplierId}','{data.Info_State}','{data.Info_Describe}',''";
                int K = DbHelperSQL.ExecuteSql(str);
            }

        }
        /// <summary>
        /// 获取入库统计
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<Warehouse_Infor>> GetPutstatisticsData(PageInput<Washouse> input)
        {
            var whereone = LinqHelper.True<BTB_Goods>();
            var inputs = input.Search;
            if (!string.IsNullOrWhiteSpace(inputs.ProductName))
            {
                Expression<Func<BTB_Goods, bool>> expression = k => k.GoodsName.Contains(inputs.ProductName);
                whereone = whereone.And(expression);
            }

            //只筛选存在入库的产品规格
            var ids = await Db.GetIQueryable<Warehouse_Information>(true).Select(x => x.Products_Id).Distinct().ToListAsync();

            var shops = await (from p in Db.GetIQueryable<BTB_GoodsSpecificationsItem>().Where(p => ids.Contains(p.GoodsSpecificationsItemID))
                               join s in Db.GetIQueryable<BTB_Goods>().Where(whereone) on p.GoodsID equals s.ID
                               select new Warehouse_Infor
                               {
                                   CreateTime = s.CreateTime,
                                   _Goods = s,
                                   _GoodsSpecificationsItem = p

                               }).OrderBy(input.SortField, input.SortType).ToListAsync();

            int counts = shops.Count;
            shops = shops.Skip((input.PageIndex - 1) * input.PageRows).Take(input.PageRows).ToList();
                      
            List<Warehouse_Infor> _Infors = new List<Warehouse_Infor>();

            foreach (var item in shops)
            {
                var q = await Db.GetIQueryable<Warehouse_Information>(false).Where(t => t.Products_Id.Equals(item._GoodsSpecificationsItem.GoodsSpecificationsItemID)).ToListAsync();
                int count = q.Count;
                decimal? num = q.Sum(t => t.Num);
                int sumcount = decimal.ToInt32((decimal)num);

                Warehouse_Infor _Infor = new Warehouse_Infor()
                {
                    ProductName = item._Goods?.GoodsName,
                    ProductsName = item._GoodsSpecificationsItem?.GoodsSpecifications,
                    PutCount = count,
                    PutNum = sumcount,
                    _Goods = item._Goods,
                    _GoodsSpecificationsItem = item._GoodsSpecificationsItem
                };
                _Infors.Add(_Infor);
            }
            //string str = "select * from ";
            return new PageResult<Warehouse_Infor>() { Data = _Infors, Total = counts };
        }


        #endregion
        #endregion

        #region 私有成员
        /// <summary>
        /// 入库明细查询分页
        /// </summary>
        private string sqlstr { get; set; } = "select t.Id,t.CreateTime,t.CreatorId,g.GoodsName as ProductName,e.GoodsSpecifications as ProductsName,e.Price,(e.Price * Num) as sumPrice,t.Num as Num,t.Info_Oldbalance,(convert(decimal(18,2),t.Info_Oldbalance)+t.Num)as ThisBlance from Warehouse_Information t  " +
                            "inner join BTB_Goods g on g.ID=t.Product_Id  " +
                            "inner join BTB_GoodsSpecificationsItem e on e.GoodsSpecificationsItemID=t.Products_Id " +
                            " order by t.CreateTime desc ";


        /// <summary>
        /// 入库明细数量查询
        /// </summary>
        private string strCount { get; set; } = "select * from Warehouse_Information t  " +
                            "inner join BTB_Goods g on g.ID=t.Product_Id  " +
                            "inner join BTB_GoodsSpecificationsItem e on e.GoodsSpecificationsItemID=t.Products_Id " ;
        #endregion
    }
}